<template>
  <div class="app-container">
    <el-card class="form-box" v-if="!hasOngoingExam">
      <div slot="header" class="clearfix">
        <span>申请考试</span>
      </div>

      <el-form :model="form" :rules="rules" ref="examForm" label-width="120px">
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入姓名"/>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"/>
        </el-form-item>

        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号码"/>
        </el-form-item>

        <el-form-item label="单位名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入单位名称"/>
        </el-form-item>

        <el-form-item label="工种/岗位" prop="jobType">
          <el-input v-model="form.jobType" placeholder="请输入工种/岗位"/>
        </el-form-item>

        <el-form-item label="作业区域" prop="deptId">
          <depart-tree-select v-model="form.deptId" :options="treeData" :props="defaultProps"/>
        </el-form-item>

        <el-form-item label="进厂时间" prop="entryTime">
          <el-date-picker v-model="form.entryTime" type="datetime" placeholder="请选择进厂时间" style="width: 100%"
                          @change="calcLeaveTime"/>
        </el-form-item>

        <el-form-item label="离厂时间" prop="leaveTime">
          <el-date-picker v-model="form.leaveTime" type="datetime" placeholder="请选择离厂时间" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="上传个人照片">
          <file-upload v-model="form.photoUrl" accept=".jpg,.jpeg,.png"/>
        </el-form-item>

        <el-form-item label="健康证明">
          <file-upload v-model="form.healthProofUrl" accept=".jpg,.jpeg,.png,.pdf"/>
        </el-form-item>

        <el-form-item label="无犯罪记录证明">
          <file-upload v-model="form.noCriminalProofUrl" accept=".jpg,.jpeg,.png,.pdf"/>
        </el-form-item>

        <el-form-item label="添加证书">

          <el-table :data="form.licenses" border stripe style="width: 100%">
            <el-table-column prop="name" label="证书名称" label-class-name="required-column">
              <template v-slot="scope">
                <el-input v-model="scope.row.name" placeholder="请输入证书名称"/>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="证书类型" label-class-name="required-column">
              <template v-slot="scope">
                <el-select v-model="scope.row.type" placeholder="请选择证书类型">
                  <el-option v-for="info in licensesInfo.type" :key="info" :label="info" :value="info"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="project" label="准操项目" label-class-name="required-column">
              <template v-slot="scope">
                <el-select v-model="scope.row.project" placeholder="请选择准操项目">
                  <el-option v-for="info in licensesInfo.project" :key="info" :label="info" :value="info"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="number" label="证书号">
              <template v-slot="scope">
                <el-input v-model="scope.row.number" placeholder="请输入证书号"/>
              </template>
            </el-table-column>
            <el-table-column prop="issueDate" label="发证日期">
              <template v-slot="scope">
                <el-date-picker v-model="scope.row.issueDate" type="date" placeholder="请选择发证日期"
                                style="width: 100%"/>
              </template>
            </el-table-column>
            <el-table-column prop="expireDate" label="到期日期">
              <template v-slot="scope">
                <el-date-picker v-model="scope.row.expireDate" type="date" placeholder="请选择到期日期"
                                style="width: 100%"/>
              </template>
            </el-table-column>
            <el-table-column prop="imgUrl" label="证书照片" label-class-name="required-column">
              <template v-slot="scope">
                <file-upload v-model="scope.row.imgUrl" accept=".jpg,.jpeg,.png"/>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="100">
              <template slot="header" slot-scope="scope">
                <el-button type="primary" size="mini" @click="addLicense">添加行</el-button>
              </template>
              <template slot-scope="scope">
                <el-button type="danger" size="mini" @click="form.licenses.splice(scope.$index, 1)">删除</el-button>
              </template>
            </el-table-column>

          </el-table>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">申请考试</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="form-box" v-else>
      <div slot="header" class="clearfix">
        <span>考试申请已存在</span>
      </div>
      <div style="text-align: center; padding: 20px;">
        <el-alert title="您已经有未完成的考试申请，请先完成或取消当前申请。" type="warning" :closable="false"/>
      </div>
    </el-card>

    <el-card class="form-box" style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span>我的申请记录</span>
      </div>

      <el-table :data="tableData" v-loading="loading" border style="width: 100%">
        <el-table-column prop="realName" label="姓名" width="100"/>
        <el-table-column prop="phone" label="手机号" width="120"/>
        <el-table-column prop="companyName" label="单位" width="120"/>
        <el-table-column prop="jobType" label="工种/岗位" width="120"/>
        <el-table-column prop="workAreaName" label="作业区域" width="120"/>
        <el-table-column label="个人照片" width="100">
          <template v-slot="scope">
            <el-image :src="scope.row.photoUrl" style="width: 60px;"/>
          </template>
        </el-table-column>
        <el-table-column label="健康证明" width="100">
          <template v-slot="scope">
            <el-image :src="scope.row.healthProofUrl" style="width: 60px;"/>
          </template>
        </el-table-column>
        <el-table-column label="无犯罪记录" width="100">
          <template v-slot="scope">
            <el-image :src="scope.row.noCriminalProofUrl" style="width: 60px;"/>
          </template>
        </el-table-column>

        <el-table-column prop="idCard" label="身份证号" width="180"/>
        <el-table-column prop="entryTime" label="进厂时间" width="160"/>
        <el-table-column prop="leaveTime" label="离厂时间" width="160"/>
        <el-table-column prop="createTime" label="申请时间" width="160"/>
        <el-table-column prop="isApply" label="申请状态" width="100">
          <template v-slot="scope">
            <el-tag v-if="scope.row.isApply === '0'" type="warning">未通过</el-tag>
            <el-tag v-else-if="scope.row.isApply === '1'" type="success">通过</el-tag>
            <el-tag v-else-if="scope.row.isApply === '2'" type="danger">驳回</el-tag>
            <el-tag v-else-if="scope.row.isApply === '3'" type="info">待审核</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isApply" label="考试状态" width="100">
          <template v-slot="scope">
            <el-tag v-if="scope.row.allPass === 0" type="info">{{ scope.row.allPassTip }}</el-tag>
            <el-tag v-else-if="scope.row.allPass === 1" type="warning">{{ scope.row.allPassTip }}</el-tag>
            <el-tag v-else-if="scope.row.allPass === 2" type="success">{{ scope.row.allPassTip }}</el-tag>
            <el-tag v-else-if="scope.row.allPass === 3" type="danger">{{ scope.row.allPassTip }}</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template v-slot="scope">
            <el-button v-if="scope.row.isApply == '2' || scope.row.isApply == '3'" size="mini" type="primary"
                       @click="handleEdit(scope.row)">
              修改
            </el-button>
            <el-popconfirm title="确定要删除该申请记录吗？" @confirm="handleDelete(scope.row)" confirm-button-text="确定"
                           cancel-button-text="取消">
              <el-button slot="reference" size="mini" type="danger" style="margin-left: 5px;">
                删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div style="text-align: right; margin-top: 10px;">
        <el-pagination background layout="prev, pager, next" :total="total" :current-page.sync="listQuery.current"
                       :page-size="listQuery.size" @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
    <el-dialog title="修改申请" :visible.sync="editDialogVisible" width="600px">
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="120px">
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="editForm.realName" placeholder="请输入姓名"/>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号"/>
        </el-form-item>

        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="editForm.idCard" placeholder="请输入身份证号"/>
        </el-form-item>

        <el-form-item label="单位名称" prop="companyName">
          <el-input v-model="editForm.companyName"/>
        </el-form-item>

        <el-form-item label="工种/岗位" prop="jobType">
          <el-input v-model="editForm.jobType"/>
        </el-form-item>

        <el-form-item label="作业区域" prop="deptId">
          <depart-tree-select v-model="editForm.deptId" :options="treeData" :props="defaultProps"/>
        </el-form-item>

        <el-form-item label="进厂时间" prop="entryTime">
          <el-date-picker v-model="editForm.entryTime" type="datetime" style="width: 100%"/>
        </el-form-item>

        <el-form-item label="离厂时间" prop="leaveTime">
          <el-date-picker v-model="editForm.leaveTime" type="datetime" style="width: 100%"/>
        </el-form-item>

        <el-form-item label="照片">
          <file-upload v-model="editForm.photoUrl"/>
        </el-form-item>

        <el-form-item label="健康证明">
          <file-upload v-model="editForm.healthProofUrl"/>
        </el-form-item>

        <el-form-item label="无犯罪记录">
          <file-upload v-model="editForm.noCriminalProofUrl"/>
        </el-form-item>

        <el-form-item label="添加证书">
          <el-table :data="editForm.licenses" border stripe style="width: 100%">
            <el-table-column prop="name" label="证书名称" label-class-name="required-column">
              <template v-slot="scope">
                <el-input v-model="scope.row.name" placeholder="请输入证书名称"/>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="证书类型" label-class-name="required-column">
              <template v-slot="scope">
                <el-select v-model="scope.row.type" placeholder="请选择证书类型">
                  <el-option v-for="info in licensesInfo.type" :key="info" :label="info" :value="info"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="project" label="准操项目" label-class-name="required-column">
              <template v-slot="scope">
                <el-select v-model="scope.row.project" placeholder="请选择准操项目">
                  <el-option v-for="info in licensesInfo.project" :key="info" :label="info" :value="info"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="number" label="证书号">
              <template v-slot="scope">
                <el-input v-model="scope.row.number" placeholder="请输入证书号"/>
              </template>
            </el-table-column>
            <el-table-column prop="issueDate" label="发证日期">
              <template v-slot="scope">
                <el-date-picker v-model="scope.row.issueDate" type="date" style="width: 100%"/>
              </template>
            </el-table-column>
            <el-table-column prop="expireDate" label="到期日期">
              <template v-slot="scope">
                <el-date-picker v-model="scope.row.expireDate" type="date" style="width: 100%"/>
              </template>
            </el-table-column>
            <el-table-column prop="imgUrl" label="证书照片" label-class-name="required-column">
              <template v-slot="scope">
                <file-upload v-model="scope.row.imgUrl"/>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="100">
              <template slot="header" slot-scope="scope">
                <el-button type="primary" size="mini" @click="addLicense">添加行</el-button>
              </template>
              <template slot-scope="scope">
                <el-button type="danger" size="mini" @click="editForm.licenses.splice(scope.$index, 1)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FileUpload from '@/components/FileUpload'
import {applyExam, applyExamList, updateApply, deleteApply} from '@/api/paper/exam'
import DepartTreeSelect from '@/components/DepartTreeSelect'
import {fetchTree} from '@/api/sys/depart/depart'
import rules from "@/utils/rules";
import {licensesInfo} from "@/utils"

export default {
  name: 'ApplyExam',
  components: {DepartTreeSelect, FileUpload},
  data() {
    return {
      licensesInfo: licensesInfo,
      emptyLicense: {
        expireDate: "",
        issueDate: "",
        name: "",
        number: "",
        project: "无",
        type: "无",
        imgUrl: ''
      },
      form: {
        userName: '',
        realName: '',
        phone: '',
        idCard: '',
        departId: '',
        companyName: '',
        jobType: '',
        workArea: '',
        entryTime: '',
        leaveTime: '',
        licenses: [],
        photoUrl: '',
        healthProofUrl: '',
        noCriminalProofUrl: '',
        certificatePhotosUrl: '',
        isApply: '3'
      },
      editDialogVisible: false,
      editForm: {
        id: '',
        userName: '',
        realName: '',
        phone: '',
        idCard: '',
        deptId: '',
        companyName: '',
        jobType: '',
        workArea: '',
        entryTime: '',
        leaveTime: '',
        licenses: {
          expireDate: "",
          issueDate: "",
          name: "",
          number: "",
          project: "无",
          type: "无"
        },
        photoUrl: '',
        healthProofUrl: '',
        noCriminalProofUrl: '',
        certificatePhotosUrl1: '',
        certificatePhotosUrl2: '',
        certificatePhotosUrl3: '',
        isApply: '3'
      },
      rules,
      listQuery: {
        current: 1,
        size: 10,
        params: {
          userName: ''
        }
      },
      defaultProps: {
        value: 'id',
        label: 'deptName',
        children: 'children'
      },
      treeData: [],
      tableData: [],
      total: 0,
      loading: false,
      hasOngoingExam: false,
    }
  },
  mounted() {
    const userName = this.$store.state.user.name
    this.form.realName = this.$store.state.user.realName
    this.form.phone = userName
    this.form.userName = userName
    this.listQuery.params.userName = userName
    this.listQuery.params.phone = userName
    this.fetchApplyList()
    fetchTree({}).then(response => {
      this.treeData = response.data
    })
  },
  methods: {
    validateLicense(licenses) {
      // 验证证书信息是否完整
      return licenses.every(license => {
        return license.name && license.type && license.project && license.imgUrl
      })

    },
    addLicense() {
      const validate = this.validateLicense(this.form.licenses)
      if (!validate) {
        this.$message.error('请填写完整的证书信息，必须填写证书名称、类型、准操项目和证书照片')
        return
      }
      this.form.licenses.push(Object.assign({}, this.emptyLicense))
    },
    calcLeaveTime() {
      // 根据进厂时间计算离厂时间 默认离厂时间为进厂时间后 2 个月
      if (this.form.entryTime) {
        const entryDate = new Date(this.form.entryTime)
        entryDate.setMonth(entryDate.getMonth() + 2)
        this.form.leaveTime = entryDate
      } else {
        this.form.leaveTime = ''
      }
    },
    handleDelete(row) {
      // 调用你自己的删除 API，比如 deleteExam(id)
      let params = {
        id: row.id
      }
      deleteApply(params).then(() => {
        this.$message.success('删除成功！')

        this.fetchApplyList()
      })
    },
    handleEdit(row) {
      this.editForm = {...row}  // 直接拷贝一份
      this.editDialogVisible = true
      this.$nextTick(() => {
        this.$refs.editFormRef && this.$refs.editFormRef.clearValidate()
      })
    },
    submitEdit() {
      const licenseRes = this.validateLicense(this.form.licenses)
      if (!licenseRes) {
        this.$message.error('请填写完整的证书信息，必须填写证书名称、类型、准操项目和证书照片')
        return
      }
      this.$refs.editFormRef.validate(valid => {
        if (valid) {
          // 这里建议调用更新接口，比如 updateExam(this.editForm)
          updateApply(this.editForm).then(() => {
            this.$message.success('修改成功，已重新提交审核')
            this.editDialogVisible = false
            this.fetchApplyList()
          })
        }
      })
    },
    fetchApplyList() {
      this.loading = true
      applyExamList(this.listQuery).then(res => {
        const {records, total} = res.data
        this.tableData = records

        const lastRecord = records.reduce((latest, current) => {
          return new Date(latest.createTime) > new Date(current.createTime) ? latest : current
        }, records[0])
        this.hasOngoingExam = ![2, 3].includes(lastRecord.allPass)

        this.total = parseInt(total)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleCurrentChange(val) {
      this.listQuery.current = val
      this.fetchApplyList()
    },
    submitForm() {
      const licenseRes = this.validateLicense(this.form.licenses)
      if (!licenseRes) {
        this.$message.error('请填写完整的证书信息，必须填写证书名称、类型、准操项目和证书照片')
        return
      }
      this.$refs.examForm.validate(valid => {
        if (valid) {
          applyExam(this.form).then(() => {
            this.$message({
              message: '申请成功，请等待审核！',
              type: 'success'
            })
            this.fetchApplyList()
          })
        } else {
          this.$message.error('请填写完整的申请信息')
        }
      })
    },
    resetForm() {
      this.$refs.examForm.resetFields()
      this.form.photoUrl = ''
      this.form.healthProofUrl = ''
      this.form.noCriminalProofUrl = ''
    }
  }
}
</script>

<style scoped>
.form-box {
  max-width: 100%;
  margin: 0 auto;
}

::v-deep div.required-column {
  &::before {
    content: '*';
    color: red;
    margin-right: 2px;
  }
}
</style>
